# -*- coding:utf-8 -*-
# @Time     :2024/3/9 17:12
# @Author   :CHNJX
# @File     :get_performance_result.py
# @Desc     :
from openpyxl import load_workbook
from datetime import datetime, timedelta
import os


def get_performance_result(performance_data_path):
    # 定义昨天的日期字符串格式
    yesterday_str = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
    yesterday_md_str = (datetime.now() - timedelta(days=1)).strftime("%m%d")
    # yesterday_md_str = "03-06"
    # 确保文件存在
    if not os.path.exists(performance_data_path):
        print("One or more files do not exist.")
        exit()

    # 加载性能数据工作簿
    performance_workbook = load_workbook(performance_data_path)

    # 初始化存储性能问题的字典
    performance_issues = {}

    # 分析每个工作表的性能数据
    cpu_res = 'pass'
    mem_res = 'pass'
    for sheet_name in performance_workbook.sheetnames:
        if yesterday_str in sheet_name:
            performance_sheet = performance_workbook[sheet_name]
            cpu_issues = []
            mem_issues = []
            for row in performance_sheet.iter_rows(min_row=2, values_only=True):
                time, cpu, mem = row
                if cpu and cpu > 90:
                    cpu_res = 'fail'
                    cpu_issues.append(f"{yesterday_md_str}-{time.strip()}-{cpu}%")
                if mem and mem > 95:
                    mem_res = 'fail'
                    mem_issues.append(f"{yesterday_md_str}-{time.strip()} - {mem}%")

            # 从工作表名称中获取型号名称
            model_name = sheet_name.split('_')[0]
            performance_issues[model_name] = {
                'cpu监控': (cpu_res, ';'.join(cpu_issues)),
                '内存监控': (mem_res, ';'.join(mem_issues))
            }
    return performance_issues
